package com.thomas.extension;

import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class Yaml2Properties extends AnAction {
    private static final String ENCODING = "UTF-8";
    private static final String SEPARCTER = ".";

    @Override
    public void update(@NotNull AnActionEvent e) {
        VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
        if(file == null || (!file.getExtension().equals("yml") && !file.getExtension().equals("yaml"))){
            e.getPresentation().setEnabledAndVisible(false);
        }
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        // TODO: insert action logic here
        transform(e.getDataContext());
    }

    public static void transform(DataContext dataContext) {
        VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
        if(file != null && (file.getExtension().equals("yml")|| file.getExtension().equals("yaml"))){
            try {
                String s = IOUtils.toString(file.getInputStream(), ENCODING);
                String srcPath = file.getPath();
                String destPath = srcPath.substring(0,srcPath.lastIndexOf("."))+".properties";
                yaml2Properties(destPath,s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void yaml2Properties(String destPath, String s) {
        List<String> lines = new LinkedList<>();
        YAMLParser parser = null;
        try {
            YAMLFactory yamlFactory = new YAMLFactory();
            parser = yamlFactory.createParser(s);
            String key = "";
            String value ;
            JsonToken token = parser.nextToken();
            while (token != null) {
                if (JsonToken.START_OBJECT.equals(token)) {
                    // "{" 表示字符串开头，不做解析
                } else if (JsonToken.FIELD_NAME.equals(token)) {
                    if (key.length() > 0) {
                        key = key + SEPARCTER;
                    }
                    key = key + parser.getCurrentName();
                    token = parser.nextToken();
                    if (JsonToken.START_OBJECT.equals(token)) {
                        continue;
                    }
                    value = parser.getText();
                    lines.add(key + "=" + value);
                    int dotOffset = key.lastIndexOf(SEPARCTER);
                    if (dotOffset > 0) {
                        key = key.substring(0, dotOffset);
                    }
                } else if (JsonToken.END_OBJECT.equals(token)) {
                    int dotOffset = key.lastIndexOf(SEPARCTER);
                    if (dotOffset > 0) {
                        key = key.substring(0, dotOffset);
                    } else {
                        key = "";
                        lines.add("");
                    }
                }
                token = parser.nextToken();
            }
            FileUtils.writeLines(new File(destPath),lines);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                parser.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
